package quan.dong.handle;

import java.util.ArrayList;
import java.util.List;

import quan.dong.common.Common;
import quan.dong.common.CommonEnums;
import quan.dong.common.Constant;
import quan.dong.common.TCPSocket;
import quan.dong.object.PriceAlert;
import android.os.Handler;
import android.os.Message;

public class GetPriceAlertList implements Runnable {
	String imeiNumber;
	Thread runner;
	TCPSocket socket;
	Handler handler;
	Boolean isAlerted;
	ArrayList<PriceAlert> priceAlerts;

	public GetPriceAlertList(String imeiNumber, Handler handler,
			Boolean isAlerted, String threadName) {
		super();
		priceAlerts = new ArrayList<PriceAlert>();
		this.imeiNumber = imeiNumber;
		this.handler = handler;
		this.isAlerted = isAlerted;
		runner = new Thread(this, threadName);
	}

	public void Start() {
		runner.start();
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		TCPSocket socket = new TCPSocket();
		try {
			boolean isConnected = socket.Create(Constant.SERVER_IP_ADDRESS,
					Constant.PORT);
			if (isConnected) {
				socket.SendExact(Common
						.intToByteArray(CommonEnums.ConnectType.GetPriceAlertList
								.ordinal()));
				byte[] buffer = imeiNumber.getBytes();
				int len = buffer.length;
				socket.SendExact(Common.intToByteArray(len));
				socket.SendExact(buffer);
				buffer = new byte[4];
				socket.ReadExact(buffer);
				int numPriceAlert = Common.byteArrayToInt(buffer);

				for (int i = 0; i < numPriceAlert; i++) {
					buffer = new byte[Constant.SIZE_PRICE_ALERT];
					socket.ReadExact(buffer);
					PriceAlert priceAlert = new PriceAlert();
					priceAlert.Deserialize(buffer);
					priceAlerts.add(priceAlert);
				}

				Message message = handler.obtainMessage(
						Constant.HANDLER_GET_PRICE_ALERT_LIST, priceAlerts);
				handler.sendMessage(message);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
